package com.fly.source.utils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.lang3.time.StopWatch;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MvnUtils
{
    /**
     * 获取本地maven仓库地址
     * 
     * @return
     * @throws IOException
     */
    public static String getMavenRepoPath()
        throws IOException
    {
        String mavenHome = Executor.execute("mvn -v").stream().filter(r -> r.startsWith("Maven home:")).map(arg -> StringUtils.substringAfter(arg, "Maven home:")).collect(Collectors.joining());
        String settings = mavenHome.trim() + "/conf/settings.xml";
        log.info("settings Path: {}", settings);
        String xmlContent = FileUtils.readFileToString(new File(settings), StandardCharsets.UTF_8);
        Properties prop = XmlUtils.xmlToProperties(xmlContent);
        String mvnRepoPath = prop.getProperty("localRepository");
        if (StringUtils.isBlank(mvnRepoPath))
        {
            mvnRepoPath = System.getProperty("user.home") + "/.m2/repository";
        }
        log.info("mvnRepo Path: {}", mvnRepoPath);
        return mvnRepoPath;
    }
    
    /**
     * 收集xxx-source.jar文件
     */
    public static void copyResource(String pomPath)
        throws IOException
    {
        StopWatch watch = new StopWatch();
        watch.start();
        
        // 指定与lib相同的目录
        File directory = new File("upload/target/lib");
        String mvnRepoPath = MvnUtils.getMavenRepoPath();
        String command = "mvn dependency:sources -DdownloadSources=true -f " + pomPath;
        Executor.execute(command).stream().filter(d -> StringUtils.contains(d, ":jar:sources:")).forEach(item -> {
            if (item.contains(":jar:sources:"))
            {
                String[] array = StringUtils.substringAfterLast(item, " ").split(":");
                String groupId, artifactId, version, path;
                if (array.length >= 5)
                {
                    try
                    {
                        groupId = array[0];
                        artifactId = array[1];
                        version = array[4];
                        path = String.format("%s\\%s\\%s\\%s\\%s-%s-sources.jar", mvnRepoPath, groupId.replace(".", "\\"), artifactId, version, artifactId, version);
                        log.info("------ path: {}   ", path);
                        FileUtils.copyFileToDirectory(new File(path), directory);
                    }
                    catch (IOException e)
                    {
                        log.error(e.getMessage(), e);
                    }
                }
            }
        });
        watch.stop();
        log.info("Run cost time ms: {}", watch.getTime(TimeUnit.MILLISECONDS));
        if (SystemUtils.IS_OS_WINDOWS && directory.exists())
        {
            Runtime.getRuntime().exec("cmd /c start " + directory.getPath());
        }
        FileUtils.forceDeleteOnExit(directory.getParentFile().getParentFile());
    }
}
